package zookeeper.client;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * Created by yangluhua on 2017/11/21 0021.
 */
public class MyWatcher implements Runnable{
    public void run() {
        try {
            //连接启动zk
            ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 500000,new Watcher() {
                // 监控所有被触发的事件
                public void process(WatchedEvent event) {
                    System.out.println("watcher ...");
                }
            });
            //设置监听器
            Watcher wc = new Watcher() {
                public void process(WatchedEvent event) {
                    // TODO Auto-generated method stub
                    if (event.getType() == Watcher.Event.EventType.NodeDataChanged) {
                        System.out.println("change");
                    }
                    if (event.getType() == Watcher.Event.EventType.NodeDeleted){
                        System.out.println("dele");
                    }
                    if(event.getType()== Watcher.Event.EventType.NodeCreated){
                        System.out.println("create");
                    }
                }

            };
            //进行轮询，其中exists方法用来询问状态，并且设置了监听器，如果发生变化，则会回调监听器里的方法。
            while(true)
            {
                zk.exists("/TestZookeeper/word1", wc);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (KeeperException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
